import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import ElementUI, {Message} from 'element-ui'
import axios from 'axios'
import VueAxios from 'vue-axios'
import 'element-ui/lib/theme-chalk/index.css'
import 'font-awesome/css/font-awesome.css'

import {postRequest} from "./utils/api";
import {putRequest} from "./utils/api";
import {getRequest} from "./utils/api";
import {deleteRequest} from "./utils/api";
import {initMenu} from "./utils/menus";

Vue.use(VueAxios, axios)
Vue.config.productionTip = false;
Vue.use(ElementUI);

//插件形式使用请求
Vue.prototype.postRequest = postRequest;
Vue.prototype.putRequest = putRequest;
Vue.prototype.getRequest = getRequest;
Vue.prototype.deleteRequest = deleteRequest;


//设置全局前置路由守卫
router.beforeEach((to, from, next) => {
    //判断是否登录，若登录则初始化菜单
    if (window.sessionStorage.getItem('tokenStr')){
      initMenu(router,store);
      if (!window.sessionStorage.getItem('user')){
          return getRequest('/user/info').then(resp=>{
              //判断用户信息是否存在
              if (resp){
                  //通过路由守卫获取用户信息并存入用户信息到sessionStorage中
                  window.sessionStorage.setItem('user',JSON.stringify(resp));
                  store.commit('INIT_CURRENTUSER',resp);
                  next();
              }
          })
      }
      next();
    } else {
          console.log("未登录，请先登录！")
         //判断是不是去登录页
          if (to.path=='/login'|| to.path=='/userlogin'|| to.path=='/mainpage' || to.path=='/register'){
              next();
          }else {
              next('/login?redirect='+to.path);
          }
    }
})

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
});
